package it.polimi.swim.servlet;

import it.polimi.swim.entity.Skill;
import it.polimi.swim.entity.SystemUser;
import it.polimi.swim.session.HelpRequestManagerBeanRemote;
import it.polimi.swim.session.SystemUserManagerBeanRemote;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Properties;

import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private Context ctx;

	public LoginServlet() {
		super();

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String mail, psw;
		SystemUser user;
		

		try {
			
			//Inizializza il contesto
			Properties env = new Properties();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL, "localhost:1099");
			InitialContext jndiContext = new InitialContext(env);

			//Connetto il session bean
			ctx = new InitialContext();
			Object ref = ctx.lookup("SystemUserManagerBean/remote");
			SystemUserManagerBeanRemote systemUserManagerBean = (SystemUserManagerBeanRemote) ref;
			
			//Recupero parametri dal form
			mail = request.getParameter("mail");
			psw = request.getParameter("psw");

			// validatelogin su session bean
			
			user = systemUserManagerBean.validateLogin(mail, psw);
			
			if (user != null) {
				// Login ok
				HttpSession session = request.getSession();
				session.setAttribute("mail", user.getMail());
				session.setAttribute("name", user.getName());
				session.setAttribute("surname", user.getSurname());
				session.setAttribute("city", user.getCity());
				session.setAttribute("id", user.getId());
				session.setAttribute("skillList", user.getSkill());
				// redirect to homeUser.jsp
				if(user.getType().compareTo("User")==0){
				request.getRequestDispatcher("/homeUser.jsp").forward(request, response);
				}else{
					request.getRequestDispatcher("/homeAdmin.jsp").forward(request, response);
				}
			}else {
				request.getRequestDispatcher("/index.jsp").forward(request, response);
			}

			} catch (Exception e) {
			e.printStackTrace();
			request.getRequestDispatcher("/index.jsp").forward(request, response);
		}

	}

}
